<template>
  <a-drawer
    :title='title'
    :width='width'
    :visible='visible'
    :confirmLoading='confirmLoading'
    @ok='handleOk'
    @close='handleCancel'
    cancelText='关闭'>
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-row :gutter='24'>
          <span v-for='(item,index) in config.list' :key='index'>
          <a-col :span='item.span||24' :md='item.md||24' :sm='item.sm||24'>
            <a-form-item
              :labelCol='item.labelCol || labelCol'
              :wrapperCol='item.wrapperCol || wrapperCol'
              :label="item.label||''"
            >
<!--              输入框-->
              <span v-if="item.type=='input'">
                  <a-input :type="item.inputType||'text'" :placeholder="item.placeholder||''"
                           :disabled='item.disabled || false'
                           v-decorator='[item.name, item.check||{}]' />
              </span>
              <!--              省市区-->
              <span v-if="item.type=='area'">
                 <j-area-linkage v-model='item.name' type='cascader' :province.sync='form.province'
                                 :city.sync='form.city' :area.sync='form.area' @change='handlePca' />
              </span>

              <!--              字典下拉框-->
              <span v-if="item.type=='j-select'">
                      <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}" :triggerChange='true'
                                         :dictCode='item.dictCode'
                                         :disabled='item.disabled || false'
                                         v-decorator='[item.name, item.check||{}]' :placeholder='item.placeholder' />
              </span>
              <!--              自定义下拉框-->
              <span v-if="item.type=='a-select'">
                     <a-select
                       v-decorator='[item.name, item.check||{}]'
                       :placeholder='item.placeholder'
                     >
                        <a-select-option v-for='(v,i) in item.option' :key='i' :value='v.value'>
                         {{ v.name }}
                        </a-select-option>
              </a-select>
              </span>
              <!--              单选框-->
              <span v-if="item.type=='a-radio'">
                 <a-radio-group v-decorator='[item.name, item.check||{}]' placeholder='优惠券类型'>
                        <a-radio v-for='(v,i) in item.option' :key='i' :value='v.value'>
                          {{ v.name }}
                        </a-radio>
                      </a-radio-group>
              </span>

              <!--              树形选择-->
              <span v-if="item.type=='tree-select'">
                     <j-tree-select
                       :placeholder='item.placeholder'
                       v-decorator='[item.name, item.check||{}]'
                       :data-type='item.dataType'
                     />
              </span>
              <!--              图片上传-->
              <span v-if="item.type=='upload'">
                     <j-image-upload class='avatar-uploader' :text='item.text'
                                     v-decorator='[item.name, item.check||{}]'></j-image-upload>
              </span>
              <!--              弹框-&#45;&#45;客户-->
              <span v-if="item.type =='springFrame'">
    <a-input-search :placeholder='item.placeholder' v-decorator='[item.name,item.check||{}]' readOnly enter-button
                    @search='custSearch(item.name,item.code,item.label,item.label2,item.listurl)' />
  <a-input type='hidden' v-decorator='[item.code]'></a-input>
</span>
              <!--              动态表格 可增加/减少行-->
            </a-form-item>
          </a-col></span>
        </a-row>
      </a-form>

    </a-spin>
    <proChose ref='prochoose' @okbro='okbropro'></proChose>
    <div
      :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
    >
      <a-button :style="{ marginRight: '8px' }" @click="handleCancel">
        取消
      </a-button>
      <a-button type="primary" @click="handleOk">
        确认
      </a-button>
    </div>
  </a-drawer>
</template>
<script>
import proChose from '@comp/cn-components/ProChose'
import { getAction, httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile, isPermit } from '@/utils/validate'
import UploadImage from '@/components/upload-image/UploadImage'
import JImageUpload from '@/components/cn-form/JImageUpload'
import Area from '@/components/utils/Area'

export default {
  name: 'formItemsDraw',
  props: {
    footerButton: {
      type: Boolean,
      default: true
    },
    tablecolumns: {
      type: Array
    },
    tabletype: {
      type: String
    },
    width: {
      type: String || Number
    },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
    urlAdd: {
      type: Object
    },
    // 输入框方法
    inputMethod: {
      type: Function,
      default: () => {
        return Function
      }

    }

  },
  data() {
    return {
      title:'新增',
      formkey: '',
      jsonInput: '',
      display: false,
      sendPro: false,
      ProductAdress: [],
      dataSurces2: [],
      formChoice: [],
      showCode: false,
      remembertext: '',
      dataSource: [],
      manobjList: [0],
      areaData: '',
      areaLinkage: '',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        telephone: {
          rules: [
            { required: true, message: '请输入联系人电话', trigger: 'submit' },
            {
              validator: function(rule, value, callback) {
                if (!isMobile(value)) {
                  callback(new Error('请输入正确的手机号码'))
                }
                callback()
              }
            }
          ]
        },
        businessLicense: {
          rules: [
            { required: true, message: '请输入营业执照号', trigger: 'submit' },
            {
              validator: function(rule, value, callback) {
                if (!isPermit(value)) {
                  callback(new Error('请输入正确的营业执照号'))
                }
                callback()
              }
            }
          ]
        },
        terminalName: {
          rules: [
            { required: true, message: '请输入门店名称' }
          ]
        },
        address: {
          rules: [
            { required: true, message: '请输入详细地址' }
          ]
        },
        linkman: {
          rules: [
            { required: true, message: '请输入联系人' }
          ]
        },
        telphone: {
          rules: [
            { required: true, message: '请输入联系电话' }
          ]
        },
        dictDataCode: {
          rules: [
            { required: true, message: '请选择渠道类型' }
          ]
        },
        terminalType: {
          rules: [
            { required: true, message: '请选择门店类型' }
          ]
        },
        terminalLevel: {
          rules: [
            { required: true, message: '请选择门店等级' }
          ]
        },
        orgCode: {
          rules: [
            { required: true, message: '请确认是否总店' }
          ]
        }
      },
      letter: ''
    }
  },
  components: { JTreeSelect, JAreaLinkage, UploadImage, JImageUpload, proChose },
  created() {
    this.initAreaData()
    // this.getlist()
    // console.log(this.areaData);
  },
  methods: {
    handlePca(code) {
      let cities = this.areaData.getText(code, '多个值').cities
      let codes = this.areaData.getText(code, '多个值').codes
      this.model.province = cities.split('/')[0]
      this.model.city = cities.split('/')[1]
      this.model.area = cities.split('/')[2]
      this.model.provinceCode = this.dealCode(codes.split('/')[0], 2).join('')
      this.model.cityCode = this.dealCode(codes.split('/')[1], 4).join('')
      this.model.areaCode = this.dealCode(codes.split('/')[2], 6).join('')
      console.log(this.model)
    },
    // params:code:编码，count位数
    dealCode(code, count) {
      console.log(code)
      let num = code.split('')
      let codes = []
      for (let i = 0; i < count; i++) {
        codes.push(num[i])
      }
      return codes
    },
    randomHexColor() { //随机生成十六进制颜色
      var hex = Math.floor(Math.random() * 16777216).toString(16) //生成ffffff以内16进制数
      while (hex.length < 6) { //while循环判断hex位数，少于6位前面加0凑够6位
        hex = '0' + hex
      }
      return '#' + hex //返回‘#'开头16进制颜色
    },
    add() {
      this.edit({})
    },
    configs(config) {
      this.form.resetFields()
      this.config = config
      this.visible = true
    },
    fornOn(cord, status) {
      // if(cord.predicates || cord.filters){
      //   cord.predicates = JSON.parse(cord.predicates)
      //   cord.filters = JSON.parse(cord.filters)
      // }
      this.edit(cord)
      this.letter = status
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      console.log(this.model)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.dataSource = []
      this.forms = {
        custName: '请选择',
        realName: '请选择',
        orgName: ''
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          that.confirmLoading = false
          that.$emit('okpopup', Object.assign({},values) , this.letter)
          that.close()

          // let method = ''
          // if (!this.model.id) {
          //   method = 'post'
          // } else {
          //   method = 'post'
          // }
          // let formData = Object.assign(this.model, values)
          // formData.tptposVos = that.dataSurces2
          // formData.remarks = that.remarks
          // //时间格式化
          // // formData.punchTime = formData.punchTime ? formData.punchTime.format('YYYY-MM-DD HH:mm:ss') : null;
          // // formData.birthday = formData.birthday ? formData.birthday.format() : null;
          // // console.log(this.areaLinkage);
          // // console.log(formData)
          // httpAction(this.urlAdd.addOrUpdateUrl, formData, method).then((res) => {
          //   if (res.success) {
          //     that.$message.success(res.message)
          //     that.$emit('ok')
          //   } else {
          //     that.$message.warning(res.message)
          //   }
          // }).finally(() => {
          //   that.confirmLoading = false
          //   //that.close();
          // })

        }
      })
    },
    handleCancel() {
      this.close()
    },
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()
      }
    },
    clickToadd() {
      if (this.forms.custName == '请选择' || this.dataSurces[0].productName == '') {
        this.$message.warning('请补充上一条供货信息再创建新的一条')
        return
      }
      const { count, manobjList, dataSurces, forms } = this
      this.dataSurces2 = dataSurces
      let dc = {}
      this.dataSurces2.forEach((item, index) => {
        dc = Object.assign(item, forms)
        item = dc
      })
      this.dataSurces = []
      this.forms = {
        custName: '请选择'
      }
      this.$message.success('新的供货信息已添加')
    },
    onDelete(key) {
      const dataSurces = [...this.dataSurces]
      this.dataSurces = dataSurces.filter(item => item !== key)
    },
    onDeleteee(key) {
      const dataSurces2 = [...this.dataSurces2]
      this.dataSurces2 = dataSurces2.filter(item => item !== key)
    },

    // getlist() {
    //   postAction(this.list).then(res => {
    //     let cust = res.result.records
    //     cust.forEach(item => {
    //
    //     })
    //   })
    // },
    handleSelectCode() {
      this.$refs.CodeConfigModal.showModal(this.userTypeTp)
    },
    handelSaveOk(ob) {
      let that = this
      if (ob != null && ob != null) {
        that.forms.custName = ob.name
        that.forms.custCode = ob.code
        // that.$nextTick(() => {
        //   that.form.setFieldsValue(pick(that.model, Object.keys(that.model)))
        // })
      }
      // 查询code
    },
// 客户选择
    custSearch(name, code, label, label2, listUrl) {
      let formconfig = [
        {
          key: code,
          label: label2
        },
        {
          key: name,
          label: label
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: label2,
            align: 'center',
            dataIndex: code,
            width: 120,
            ellipsis: true
          },
          {
            title: label,
            align: 'center',
            dataIndex: name,
            width: 120,
            ellipsis: true
          }
        ],
        list: listUrl,
        multiple: false,
        columW: 10
      }
      this.name = label
      let a = name
      let b = code
      let dataSource = [{
        [name]: this.form.getFieldValue(name),
        [code]: this.form.getFieldValue(code)
      }]
      this.$refs.prochoose.rowKey = name
      this.$refs.prochoose.edit(formconfig, tableconfig, code, name, dataSource)
    },

    okbropro(record, status, status2) {

      console.log(record, status, status2)
      if (record) {
        this.form.setFieldsValue({
          [status]: record[0][status],
          [status2]: record[0][status2]
        })
      }

    }
  }
}
</script>

<style scoped>
.gonghuoxinxi {
  width: 100%;
  border-bottom: 1px dashed black;
  margin: 10px 0;
  padding: 15px 5px;
  display: flex;
  flex-direction: column;
}
</style>